<script setup>
import { onMounted, ref } from 'vue';
import './login.scss'
import { useRouter } from 'vue-router';
import { loginAPI } from '@/apis/login';
import useDataStore from '~/src/store';
import { storeToRefs } from 'pinia';

const dataStore = useDataStore()
const { isMobile } = storeToRefs(dataStore)

const router = useRouter()

defineOptions({
    name: 'Login'
})



let username = ref()    // 用户名
let password = ref()    // 密码

/* ------------------------------ 点击立即注册跳转到注册页面 ----------------------------- */
const toRegisterAction = () => {
    router.push({ name: 'register' })
}


/* ---------------------------------- 点击登录 ---------------------------------- */
const loginAction = async () => {
    let data = await loginAPI(username.value, password.value)
    if (data.code === 200) {
        // 把返回的token存在localstorage中
        localStorage.setItem('token', data.token)
        // 把返回的userinfo存在仓库中
        localStorage.setItem('userInfo', JSON.stringify(data.userInfo))
        localStorage.setItem('isLogin', 'true')
        dataStore.setUserInfo(data.userInfo)
        dataStore.setIsLogin(true)

        ElMessage({
            message: '登录成功',
            type: 'success'
        })
        router.push({ name: 'home' })
    } else {
        ElMessage({
            message: data.msg || '登录失败',
            type: 'error'
        })
    }
}

</script>

<template>
    <div class="page">
        <div class="container">
            <div class="formbox">
                <div class="poster">
                    <img src="../../assets/images/poster.jpg" alt="">
                </div>
                <div class="form">
                    <div class="form-title">登 录</div>
                    <div class="form-wel">welcome to shoesdog</div>
                    <el-form :model="form" label-width="120px" class="elform">
                        <el-form-item label="账号" class="elformitem" label-width="auto">
                            <el-input size="large" v-model="username" placeholder="在这里输入用户名" />
                        </el-form-item>
                        <el-form-item label="密码" class="elformitem" label-width="auto">
                            <el-input size="large" v-model="password" placeholder="在这里输入密码" show-password />
                        </el-form-item>
                        <div class="form-btn">
                            <el-button @click.prevent="loginAction" class="btn1" size='large' round auto-insert-space
                                type="primary" color="#626aef">登录</el-button>
                            <div class="btn-text">没有账号？<span @click="toRegisterAction">立即注册</span></div>
                        </div>
                    </el-form>
                </div>

            </div>

        </div>
    </div>
</template>

<style scoped lang='scss'></style>